package com.dmooo.yxmmerchant;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NotificationManagerCompat;
import android.view.View;
import android.widget.RadioGroup;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.common.dialog.MyDialog;
import com.common.net.entity.SubjectPost;
import com.common.net.listener.HttpOnNextListener;
import com.common.net.subscribers.ProgressSubscriber;
import com.common.net.util.JSONUtils;
import com.common.util.LogUtil;
import com.common.util.SPUtils;
import com.common.util.StartActivityUtil;
import com.dmooo.yxmmerchant.app.YZXApplication;
import com.dmooo.yxmmerchant.base.BaseActivity;
import com.dmooo.yxmmerchant.common.Config;
import com.dmooo.yxmmerchant.domain.MerchantInfoBean;
import com.dmooo.yxmmerchant.domain.Msg;
import com.dmooo.yxmmerchant.http.HttpManager;
import com.dmooo.yxmmerchant.util.Notify;
import com.dmooo.yxmmerchant.view.contract.MainContract;
import com.dmooo.yxmmerchant.view.presenter.MainPresenter;
import com.dmooo.yxmmerchant.view.ui.ChatActivity;
import com.dmooo.yxmmerchant.view.ui.SelKfActivity;
import com.google.gson.JsonObject;
import com.hjq.permissions.Permission;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.exceptions.HyphenateException;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import me.leolin.shortcutbadger.ShortcutBadger;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.MainView {
    @BindView(R.id.rg_nav)
    RadioGroup rgNav;
    private Fragment f1, f2, f3, f5,f4;
    private FragmentManager fm;
    private Fragment currentFragment = new Fragment();

    @Override
    protected int getLayout() {
        setStatusBar(Color.WHITE);
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((EaseConversationListFragment)f4).setName11(SPUtils.get(this,Config.ADMIN_NAME,"会话列表").toString());
        int count = EMClient.getInstance().chatManager().getUnreadMessageCount();
        ShortcutBadger.applyCount(this, count); //for 1.1.4+
//        mPresenter.getMerchantInfo(token);
    }
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            if(resultCode==RESULT_OK){
                if(requestCode==Config.SELECT_PHOTO){
//                    MyGoodsOrderFragment.file=(new File(getRealFilePath(mContext,Matisse.obtainResult(data).get(0))));
//                    GlideUtils.showImageView(mContext,mContext.getResources().getDrawable(R.mipmap.defaultpicture_classify),MyGoodsOrderFragment.file.getAbsolutePath(),MyGoodsOrderFragment.imgAdd);
                }
            }
    }

    @Override
    protected void initEventAndData() {
        EventBus.getDefault().register(this);
        fm = getSupportFragmentManager();
//        f1 = fm.findFragmentById(R.id.frag_index);
//        f2 = fm.findFragmentById(R.id.frag_mall);
//        f3 = fm.findFragmentById(R.id.frag_service);
        f4= fm.findFragmentById(R.id.frag_kf);
        f5 = fm.findFragmentById(R.id.frag_mine);
        ((EaseConversationListFragment)f4).setSelKeFu(new EaseConversationListFragment.SelKeFu() {
            @Override
            public void onSel() {
                Bundle bundle=new Bundle();
                bundle.putString("type","0");
                StartActivityUtil.startActivity(MainActivity.this, SelKfActivity.class, bundle);
            }
        });
        NotificationManagerCompat notification = NotificationManagerCompat.from(this);
        boolean isEnabled = notification.areNotificationsEnabled();
        if (!isEnabled) {
            MyDialog.showMaterialDialog(getSupportFragmentManager(), "通知打开", "请求打开通知权限", "下次", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            }, "打开", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gotoSet();
//                    NotificationUtil.OpenNotificationSetting(MainActivity.this, new NotificationUtil.OnNextLitener() {
//                        @Override
//                        public void onNext() {
//
//                        }
//                    });
                }
            }).show();
        }else{
            if ("1".equals(SPUtils.get(YZXApplication.getContext(), Config.IS_USER_OPEN_INFORM, "0"))) {
            }else{
//                MyDialog.showMaterialDialog(getSupportFragmentManager(), "通知打开", "请求打开通知权限", "下次", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                    }
//                }, "打开", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        StartActivityUtil.startActivity(MainActivity.this,SettingActivity.class);
////                    NotificationUtil.OpenNotificationSetting(MainActivity.this, new NotificationUtil.OnNextLitener() {
////                        @Override
////                        public void onNext() {
////
////                        }
////                    });
//                    }
//                }).show();
            }
        }
        Config.AUTH=SPUtils.get(this,Config.AUTH_RULE,"").toString();
        Config.ADMIN_NAME=SPUtils.get(this,Config.ADMIN_NAME_2,"").toString();
        findViewById(R.id.rg_index).setVisibility(View.VISIBLE);
        findViewById(R.id.rg_kf).setVisibility(View.GONE);
        findViewById(R.id.rg_mall2).setVisibility(View.GONE);
        rgNav.check(R.id.rg_index);
        fm.beginTransaction().hide(f5).show(f4).commit();
        setStatusBar(getResources().getColor(R.color.colorPrimary));
        rgNav.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rg_index:
                        fm.beginTransaction().hide(f5).show(f4).commit();
                        setStatusBar(getResources().getColor(R.color.colorPrimary));
//                        setStatusBar(Color.TRANSPARENT);
                        break;
                    case R.id.rg_mine:
                        fm.beginTransaction().hide(f4).show(f5).commit();
                        setStatusBar(getResources().getColor(R.color.colorPrimary));
//                        setStatusBar(Color.TRANSPARENT);
                        break;
                }
            }
        });

            findViewById(R.id.rg_service).setVisibility(View.GONE);
            ((EaseConversationListFragment) f4).setConversationListItemClickListener(new EaseConversationListFragment.EaseConversationListItemClickListener() {
                @Override
                public void onListItemClicked(EMConversation conversation) {
                    if(conversation.getLatestMessageFromOthers()==null){
                        Bundle bundle=new Bundle();
                        try {
                            bundle.putString("name",conversation.getAllMessages().get(0).getStringAttribute("nickto"));
                        } catch (HyphenateException e) {
                            bundle.putString("name",conversation.conversationId());
                        }
                        bundle.putString("uuid",conversation.conversationId());
                        bundle.putString("type","0");
                        StartActivityUtil.startActivity(MainActivity.this,ChatActivity.class,bundle);
                        return;
                    }
                    Bundle bundle=new Bundle();
                    try {
                        bundle.putString("name",conversation.getLatestMessageFromOthers().getStringAttribute("nick"));
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                    bundle.putString("uuid",conversation.getLatestMessageFromOthers().getFrom());
                    StartActivityUtil.startActivity(MainActivity.this,ChatActivity.class,bundle);
                }
            });
        checkVersion();
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
    }

//    private FragmentTransaction switchFragment(Fragment targetFragment) {
//        FragmentTransaction transaction = getSupportFragmentManager()
//                .beginTransaction();
//        if (!targetFragment.isAdded()) {
//            if (currentFragment != null) {
//                transaction.hide(currentFragment);
//            }
//            transaction.add(R.id.frame, targetFragment, targetFragment.getClass().getName());
//        } else {
//            transaction
//                    .hide(currentFragment)
//                    .show(targetFragment);
//        }
//        currentFragment = targetFragment;
//        return transaction;
//    }

    public boolean isDebug(Context context){
        boolean isDebug = context.getApplicationInfo()!=null&&
                (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)!=0;
        LogUtil.d("dsfasdfsd",isDebug+"");
        return isDebug;
    }
    private void checkVersion() {
        Map<String, Object> map = new HashMap<>();
        SubjectPost post = new SubjectPost(new ProgressSubscriber(new HttpOnNextListener() {
            @Override
            public void onNext(Object o) {
                JsonObject object = JSONUtils.getAsJsonObject(o);
                Config.POINT_VALUE = object.get("point_value").getAsString();
                if(isDebug(MainActivity.this)){
                    String downloadUrl = object.get("down_android_test").getAsString();
                    String localVersion = "1.0";
                    try {
                        PackageInfo packageInfo = getApplicationContext()
                                .getPackageManager()
                                .getPackageInfo(getPackageName(), 0);
                        localVersion = packageInfo.versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    String lastVersion = object.get("version_android_test").getAsString();
//                final String dd =  object.get("down_android").getAsString();
                    final String content = object.get("content_android").getAsString();
                    String localStr = localVersion.replaceAll("\\.", "");
                    String lastStr = lastVersion.replaceAll("\\.", "");
                    try {
                        if (Integer.parseInt(localStr) < Integer.parseInt(lastStr)) {
                            //只有当本地的小于线上的版本时才进行更新
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showVersionDialog(content, downloadUrl);
                                }
                            });
                        }
                    } catch (Exception e) {
//                        if (!localVersion.equals(lastVersion)) {
//                            //弹出显示最新版本提示去下载
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    showVersionDialog(dd, content);
//                                }
//                            });
//                        }
                    }
                }else{
                    String downloadUrl = object.get("down_android").getAsString();
                    String localVersion = "1.0";
                    try {
                        PackageInfo packageInfo = getApplicationContext()
                                .getPackageManager()
                                .getPackageInfo(getPackageName(), 0);
                        localVersion = packageInfo.versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    String lastVersion = object.get("version_android").getAsString();
//                final String dd =  object.get("down_android").getAsString();
                    final String content = object.get("content_android").getAsString();
                    String localStr = localVersion.replaceAll("\\.", "");
                    String lastStr = lastVersion.replaceAll("\\.", "");
                    try {
                        if (Integer.parseInt(localStr) < Integer.parseInt(lastStr)) {
                            //只有当本地的小于线上的版本时才进行更新
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showVersionDialog(content, downloadUrl);
                                }
                            });
                        }
                    } catch (Exception e) {
//                        if (!localVersion.equals(lastVersion)) {
//                            //弹出显示最新版本提示去下载
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    showVersionDialog(dd, content);
//                                }
//                            });
//                        }
                    }
                }
            }

            @Override
            public void onFail(Object o) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onComplete() {

            }
        }, this, false, false, "登录中"), map);
        HttpManager.getInstance().version(post);
    }
    private void showVersionDialog(String content, String url) {
        if (!checkPermission(Permission.WRITE_EXTERNAL_STORAGE)) {
            requestPermission(Permission.WRITE_EXTERNAL_STORAGE, "存储权限");
        } else {
            AllenVersionChecker
                    .getInstance()
                    .downloadOnly(
                            UIData.create().setTitle("源溪默商户版").setContent(content).setDownloadUrl(url)
                    ).setSilentDownload(false).setShowNotification(true).setForceRedownload(true).executeMission(this);
        }
    }
    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            int count = EMClient.getInstance().chatManager().getUnreadMessageCount();
            ShortcutBadger.applyCount(mContext, count); //for 1.1.4+
            ((EaseConversationListFragment)f4).refresh();
//            Notify notify=new Notify(MainActivity.this);
//            try {
//                notify.setNotification(messages.get(0).getStringAttribute("nick"),"向你发起了咨询",messages.get(0).getStringAttribute("nick"),messages.get(0).getFrom());
//            } catch (HyphenateException e) {
//                e.printStackTrace();
//            }
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };


    @Override
    protected void createPresenter() {
//        mPresenter=new MainPresenter(this,this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Msg event) {
        if(event.message.contains("jump_to_order")){
            rgNav.check(R.id.rg_mall2);
        }else if(event.message.equals("jump_to_income")){
            rgNav.check(R.id.rg_service);
        }
    }
    @Override
    public void showMerchantInfoBean(MerchantInfoBean merchantInfoBean) {
        YZXApplication.setMerchantInfoBean(merchantInfoBean);
        EventBus.getDefault().post(new Msg("show"));
    }

    @Override
    public void editMerchantInfoBeanSuccess() {

    }
    @Override
    public void editMerchantAvatarSuccess() {

    }
}
